(in-package :lilu-swank-client)

(defparameter *default-remote-debugger* :emacs)
(defparameter *default-swank-host* "localhost")


(defun get-file (filename)
  (let ((so (make-string-output-stream)))
    (with-open-file (stream filename)
      ;; remove shebang
      (let ((first-char (read-char stream))
	          (second-char (read-char stream)))
        (cond
          ((and (char= first-char #\#) (char= second-char #\!))
           (read-line stream))
          (t (unread-char second-char stream)
	           (unread-char first-char stream))))
      (loop for line = (read-line stream nil)
            while line do
              (write-string line so)))
    (get-output-stream-string so)))

(defun remote-eval-string (content &key (port lilu-swank:*default-swank-port*)
                                     (host *default-swank-host*)
                                     (debugger *default-remote-debugger*))
  (let ((res nil))
    (handler-case
        (swank-client:with-slime-connection (connection host port)
          (setf res (swank-client:slime-eval
                     (list 'lilu-swank-client::eval-script content :debugger debugger)
                     connection))
          (swank-client:slime-close connection)
          (bt:join-thread
           (find-if #'(lambda (n)
                        (alexandria:starts-with-subseq "swank dispatcher" n))
                    (bt:all-threads)
                    :key #'bt:thread-name)))
      (swank-client:slime-network-error ()
        (format t "Connection Error: ~A ~A~%" host port)))
    (dolist (r res)
      (format t "~A~%" res))
    res
    ))

(defun remote-eval-script (file &key (port lilu-swank:*default-swank-port*)
                                  (host *default-swank-host*)
                                  (debugger *default-remote-debugger*))
  (let ((content (get-file file)))
    (remote-eval-string content :port port :host host :debugger debugger)))

(defun remote-eval-strings (evals &key (port lilu-swank:*default-swank-port*)
                                    (host *default-swank-host*)
                                    (debugger *default-remote-debugger*))
  (let ((content (apply #'concatenate 'string evals)))
    (remote-eval-string content :port port :host host :debugger debugger)))
